/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufrn.engcomp.mpc.util;

import com.mathworks.toolbox.javabuilder.MWClassID;
import com.mathworks.toolbox.javabuilder.MWComplexity;
import com.mathworks.toolbox.javabuilder.MWNumericArray;
import org.apache.commons.math.linear.Array2DRowRealMatrix;
import org.apache.commons.math.linear.RealMatrix;

/**
 *
 * @author Felipe
 */
public class MATLABUtils {
    public static MWNumericArray convertMatrixJavaToMATLAB(RealMatrix javaMatrix) {
        if (javaMatrix != null) {
            MWNumericArray matlabMatrix = MWNumericArray.newInstance(new int[] { javaMatrix.getRowDimension(), javaMatrix.getColumnDimension() }, MWClassID.DOUBLE, MWComplexity.REAL);

            for (int i=0; i<javaMatrix.getRowDimension(); i++) {
                for (int j=0; j<javaMatrix.getColumnDimension(); j++) {
                    matlabMatrix.set(new int[] { i + 1, j + 1 }, javaMatrix.getEntry(i, j));
                }
            }

            return matlabMatrix;
        } else {
            return MWNumericArray.newInstance(new int[] { 0, 0 }, MWClassID.DOUBLE, MWComplexity.REAL);
        }
    }
    
    public static RealMatrix convertMatrixMATLABToJava(MWNumericArray matlabMatrix) {
        int[] dimensions = matlabMatrix.getDimensions();
        
        RealMatrix javaMatrix = new Array2DRowRealMatrix(dimensions[0], dimensions[1]);
        
        for (int i=0; i<dimensions[0]; i++) {
            for (int j=0; j<dimensions[1]; j++) {
                javaMatrix.setEntry(i, j, (Double) matlabMatrix.get(new int[] { i, j }));
            }
        }
        
        return javaMatrix;
    }
}
